package com.xaicode.learn.netty.codec;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/13 0013 23:29
 */
@Slf4j
public class NettyServerHandlerWithSimpleChannel extends SimpleChannelInboundHandler<StudentPOJO.Student> {

    // read client msg
    @Override
    public void channelRead0(ChannelHandlerContext ctx, StudentPOJO.Student student) throws Exception {

        log.info("ctx: {}", ctx);

        // read client student
        log.info("receive client Student id={}, name={}", student.getId(), student.getName());
    }

    // read client msg complete
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

        log.info("read client msg complete");

        // write and flush
        ctx.writeAndFlush(Unpooled.copiedBuffer("server complete: hello client", CharsetUtil.UTF_8));
    }

    // on exception
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
